<template>
  <div class="detail-wrapper customer-detail-wrapper">
    <PageTitle title="返回客户列表" />

    <div
      class="detail-content"
      v-if="Object.keys(detail).length">
      <el-scrollbar>
        <div class="detail-box">
          <div class="detail-title-box">
            <span>基本信息</span>
          </div>

          <div class="detail-info base-info">
            <div class="info-box">
              <div class="item">
                <p>客户账号</p>
                <p>{{ detail.member.accountName }}</p>
              </div>
              <div class="item">
                <p>客户名称</p>
                <p>{{ detail.member.nickname }}</p>
              </div>
              <div class="item">
                <p>客户类型</p>
                <p>{{ detail.member.type === 1 ? '直客' : '伙伴' }}</p>
              </div>
           
              <div class="item" v-if="userStore.user.type!==4">
                <p>归属伙伴</p>
                <div>
                  <span>{{ detail.member.attributionName }}</span>
                  <el-popover
                    placement="bottom"
                    :width="330"
                    trigger="click"
                    popper-class="popover-wrapper"
                    ref="popoverAppoint"
                    @hide="
                      accountName = '';
                      form.accountName = '';
                      form.smsCode = '';
                    ">
                    <template #reference v-if="detail.member.type!==4">
                      <el-text
                        type="primary"
                        class="text-btn">
                        重新指定
                      </el-text>
                    </template>
                    <div class="popover-content">
                      <el-form
                        label-position="top"
                        :model="form">
                        <el-form-item label="将指定新的归属伙伴">
                          <div class="content-item">
                            <div class="content-item-box">
                              <el-input
                                v-model="accountName"
                                placeholder="输入伙伴账号" />
                              <el-button
                                type="primary"
                                text
                                bg
                                @click="findFn">
                                检索
                              </el-button>
                            </div>
                            <p>新伙伴为：{{ form.accountName }}</p>
                          </div>
                        </el-form-item>
                        <el-form-item :label="codeLabel">
                          <div class="content-item">
                            <div class="content-item-box">
                              <el-input
                                v-model="form.smsCode"
                                placeholder="请输入" />
                              <GetMsgCode />
                            </div>
                          </div>
                        </el-form-item>
                      </el-form>

                      <div class="btn-box">
                        <el-button
                          type="primary"
                          @click="confirmAppoint">
                          确定
                        </el-button>
                        <el-button @click="cancelAppoint">取消</el-button>
                      </div>
                    </div>
                  </el-popover>
                </div>
              </div>
             
              <div class="item">
                <p>归属伙伴上级</p>
                <p>{{ detail.member.upAttributionName }}</p>
              </div>
              <div class="item">
                <p>客户类型</p>
                <p>{{ detail.member.type === 1 ? '直客' : '伙伴' }}</p>
              </div>
              <div class="item">
                <p   >备注</p>
                <div>
                  <span>{{ detail.member.remark==null?"":detail.member.remark }}</span>
                  <el-popover
                    placement="bottom"
                    :width="330"
                    trigger="click"
                    popper-class="popover-wrapper"
                    ref="popoverIdentity"
                    @hide="
                      formLevel.remark = ''; 
                    ">
                    <template #reference>
                      <el-text 
                        class="text-btn" style="color: #0f40f5;">
                        修改
                      </el-text>
                    </template>
                    <div class="popover-content"> 

                      <el-form
                        label-position="top" 
                        :model="formLevel"> 
                        <el-form-item   >
                          <div class="content-item">
                            <div class="content-item-box">
                              <el-input
                                v-model="formLevel.remark"
                                placeholder="请输入" /> 
                            </div>
                          </div>
                        </el-form-item>
                      </el-form>

                      <div class="btn-box">
                        <el-button
                          type="primary"
                          @click="confirmRemark">
                          确定
                        </el-button>
                        <el-button @click="cancelIdentity">取消</el-button>
                      </div>
                    </div>
                  </el-popover>
                </div>
              </div>
            </div>
            <div class="info-box">
              <div class="item">
                <p>手机号</p>
                <p>{{ detail.member.mobile }}</p>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-box">
          <div class="detail-title-box">
            <span>财务信息</span>
            <el-text
              type="primary"
              @click="$router.push({ name: 'logger', query: { memberId: detail.member.id } })">
              资金划拨操作记录
            </el-text>
          </div>

          <div class="detail-info money-info">
            <div class="item">
              <p>客户账户余额</p>
              <p>{{ userStore.user.type === 3 ? detail.member.money : '******' }}</p>
            </div>
            <div class="item">
              <p>客户算力券余额</p>
              <div>
                <span>{{ detail.member.voucherMoney }}</span>
                <el-popover
                  placement="bottom"
                  :width="330"
                  trigger="click"
                  popper-class="popover-wrapper"
                  ref="popoverSend"
                  @hide="
                    form.voucherMoney = '';
                    form.addReason = '';
                    form.smsCode = '';
                    userStore.getUser();
                  ">
                  <template #reference>
                    <el-text
                      type="primary"
                      class="text-btn">
                      赠送
                    </el-text>
                  </template>
                  <div class="popover-content">
                    <el-form
                      label-position="top"
                      :model="form">
                      <el-form-item label="本次赠送算力券金额为">
                        <div class="content-item">
                          <div class="content-item-box">
                            <el-input
                              v-model="form.voucherMoney"
                              placeholder="请输入" />
                            <span>元</span>
                          </div>
                          <p class="color-gray">余额：{{ userStore.user.voucher }}</p>
                        </div>
                      </el-form-item>
                      <el-form-item label="赠送原因">
                        <div class="content-item">
                          <div class="content-item-box">
                            <el-input
                              v-model="form.addReason"
                              placeholder="请输入" />
                          </div>
                        </div>
                      </el-form-item>
                      <el-form-item :label="codeLabel">
                        <div class="content-item">
                          <div class="content-item-box">
                            <el-input
                              v-model="form.smsCode"
                              placeholder="请输入" />
                            <GetMsgCode />
                          </div>
                        </div>
                      </el-form-item>
                    </el-form>

                    <div class="btn-box">
                      <el-button
                        type="primary"
                        @click="confirmSend">
                        确定
                      </el-button>
                      <el-button @click="cancelSend">取消</el-button>
                    </div>
                  </div>
                </el-popover>
              </div>
            </div>
            <div class="item">
              <p>折扣率</p>
              <p>{{ detail.member.discountRatio }}</p>
            </div>
          </div>
        </div>

        <div class="detail-box">
          <div class="detail-title-box">
            <span>数据概览</span>
          </div>

          <div class="detail-info data-info">
            <div class="data-top-box">
              <div class="item-box">
                <div class="amout-box">
                  <p>上月消耗总金额</p>
                  <p>{{ detail.lastMonthPriceTotal }}</p>
                </div>

                <div class="process-box">
                  <div class="process-item">
                    <span class="tag-name">预付费金额</span>
                    <div class="tag-content">
                      <el-progress
                        :stroke-width="15"
                        :show-text="false"
                        color="#BD3124"
                        :percentage="handlePercentage(1, 1)" />
                      <span>{{ detail.lastTakePrice }}</span>
                    </div>
                  </div>
                  <div class="process-item">
                    <span class="tag-name">后付费金额</span>
                    <div class="tag-content">
                      <el-progress
                        :stroke-width="15"
                        :show-text="false"
                        color="#7F83F7"
                        :percentage="handlePercentage(1, 2)" />
                      <span>{{ detail.lastBackPrice }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <div class="item-box">
                <div class="amout-box">
                  <p>本月消耗总金额</p>
                  <p>{{ detail.monthPriceTotal }}</p>
                </div>

                <div class="process-box">
                  <div class="process-item">
                    <span class="tag-name">预付费金额</span>
                    <div class="tag-content">
                      <el-progress
                        :stroke-width="15"
                        :show-text="false"
                        color="#BD3124"
                        :percentage="handlePercentage(2, 1)" />
                      <span>{{ detail.takePrice }}</span>
                    </div>
                  </div>
                  <div class="process-item">
                    <span class="tag-name">后付费金额</span>
                    <div class="tag-content">
                      <el-progress
                        :stroke-width="15"
                        :show-text="false"
                        color="#7F83F7"
                        :percentage="handlePercentage(2, 2)" />
                      <span>{{ detail.backPrice }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div
              class="data-bottom-box"
              id="chartBox"></div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
  import { ElMessage } from 'element-plus';

  import { getMemberDetail, addVoucherMoney, changePartner,getAgentInfo,checkPartner,updateMemberRemark } from '@/api/index'; 

  import PageTitle from '@/components/PageTitle.vue';
  import GetMsgCode from '@/components/GetMsgCode.vue';

  import echarts from '@/utils/echarts.js';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { useUserStore } from '@/stores/user';
  import { ref } from 'vue';
  const userStore = useUserStore();

  let form = reactive({
    voucherMoney: '',
    addReason: '',
    smsCode: '',
    accountName: ''
  });
  let formLevel  = reactive({
    remark:""
  })
  const codeLabel = `输入手机号为 ${userStore.user.mobile} 的验证码`;
  const popoverIdentity = ref(null)
  // 指定伙伴
  let accountName = ref('');

  function findFn() {
    form.accountName = '';

    checkPartner({
      accountName: accountName.value
    }).then(res => {
      form.accountName = res.data;
    });
  }
  function cancelIdentity() {
    popoverIdentity.value.hide();  
  }
  function confirmRemark() {
    let {remark} = formLevel
    updateMemberRemark({
      remark:remark,
      partnerId: Number(route.query.id)
    }).then((res)=>{
      ElMessage.success('修改成功');
      getMemberInfo();
      popoverIdentity.value.hide(); 
    })
  }
  function cancelTransfer() {
    popoverTransfer.value.hide();
  }
  function codeRest() {
    form.smsCode = '';
  }

  const popoverAppoint = ref(null);

  function confirmAppoint() {
    const { accountName, smsCode } = form;

    if (!accountName) {
      ElMessage.error('请输入新伙伴信息');
      return;
    }
    if (!smsCode) {
      ElMessage.error('请输入验证码');
      return;
    }
    const partnerId = ""
    getAgentInfo(accountName).then(res=>{
      if(res.success){
        partnerId = res.data.id
      }
    })

    changePartner({
      userId: detail.value.member.id,
      partnerId,
      smsCode,
      userType:"CUSTOMER"
    }).then(res => {
      ElMessage.success('已重新指定');
      popoverAppoint.value.hide();
      codeRest();
      getMemberInfo();
    });
  }

  function cancelAppoint() {
    popoverAppoint.value.hide();
    codeRest();
  }

  // 赠送
  const popoverSend = ref(null);

  function confirmSend() {
    const { voucherMoney, addReason, smsCode } = form;

    if (!voucherMoney) {
      ElMessage.error('请输入赠送金额');
      return;
    }
    if (!smsCode) {
      ElMessage.error('请输入验证码');
      return;
    }

    addVoucherMoney({
      remark:addReason,
      smsCode,
      type: 'GIVE',
      userId: detail.value.member.id,
      userType:"CUSTOMER",
      voucher:voucherMoney
    }).then(res => {
      ElMessage.success('已赠送');
      popoverSend.value.hide();
      codeRest();
      getMemberInfo();
    });
  }

  function cancelSend() {
    popoverSend.value.hide();
    codeRest();
  }

  function handlePercentage(month, type) {
    let res = 0;

    if (month === 1) {
      if (detail.value.lastMonthPriceTotal) {
        if (type === 1) {
          res = (detail.value.lastTakePrice / detail.value.lastMonthPriceTotal) * 100;
        } else {
          res = (detail.value.lastBackPrice / detail.value.lastMonthPriceTotal) * 100;
        }
      }
    } else {
      if (detail.value.monthPriceTotal) {
        if (type === 1) {
          res = (detail.value.takePrice / detail.value.monthPriceTotal) * 100;
        } else {
          res = (detail.value.backPrice / detail.value.monthPriceTotal) * 100;
        }
      }
    }

    return res;
  }

  function initLineChart() {
    let chartDom = document.getElementById('chartBox');
    if (!chartDom) {
      return;
    } else {
      echarts.dispose(chartDom);
    }

    setTimeout(() => {
      console.log(detail.value.monthList);
      let myChart = echarts.init(chartDom);
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          top: '8%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: detail.value.monthList.month || []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '预付费',
            type: 'line',
            stack: 'Total',
            data: detail.value.monthList.oneMoneyList || []
          },
          {
            name: '后付费',
            type: 'line',
            stack: 'Total',
            data: detail.value.monthList.twoMoneyList || []
          }
        ]
      };

      myChart.setOption(option, true);
    }, 300);
  }

  let detail = ref({});

  function getMemberInfo() {
    getMemberDetail({
      memberId: Number(route.query.id)
    }).then(res => {
      res.data.member.money = parseFloat(res.data.member.money.toFixed(2)) 
      res.data.member.voucherMoney = parseFloat(res.data.member.voucherMoney.toFixed(2)) 
      res.data.lastMonthPriceTotal = parseFloat(res.data.lastMonthPriceTotal.toFixed(2)) 
      res.data.lastTakePrice = parseFloat(res.data.lastTakePrice.toFixed(2)) 
      res.data.lastBackPrice = parseFloat(res.data.lastBackPrice.toFixed(2)) 
      res.data.monthPriceTotal =parseFloat(res.data.monthPriceTotal.toFixed(2))  
      res.data.takePrice =parseFloat(res.data.takePrice.toFixed(2))  
      res.data.backPrice = parseFloat(res.data.backPrice.toFixed(2)) 
      detail.value = res.data;

      nextTick(() => {
        initLineChart();
      });
    });
  }

  onMounted(() => {
    getMemberInfo();
  });
</script>

<style lang="scss" scoped>
  .customer-detail-wrapper {
    .base-info {
      .info-box {
        display: flex;
        align-items: center;

        &:first-of-type {
          margin-bottom: 40px;
        }

        .item {
          min-width: 200px;
          margin-right: 20px;

          p {
            &:nth-of-type(1) {
              margin-bottom: 10px;
              color: #888;
            }

            .el-text {
              margin-left: 10px;
              cursor: pointer;
            }
          }
        }
      }
    }

    .money-info {
      display: flex;
      align-items: center;
      .item {
        min-width: 200px;
        margin-right: 20px;

        p {
          &:nth-of-type(1) {
            margin-bottom: 10px;
            color: #888;
          }

          .el-text {
            margin-left: 10px;
            cursor: pointer;
          }
        }
      }
    }

    .data-info {
      .data-top-box {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .item-box {
          width: 46%;

          .amout-box {
            margin-bottom: 10px;

            p {
              &:nth-of-type(1) {
                margin-bottom: 10px;
                color: #888;
              }
            }
          }

          .process-box {
            .process-item {
              display: flex;
              align-items: center;
              margin-bottom: 10px;

              .tag-name {
                flex-shrink: 0;
                margin-right: 10px;
                color: #888;
              }

              .tag-content {
                flex: 1;
                display: flex;
                align-items: center;

                .el-progress {
                  flex: 1;
                  margin-right: 10px;
                }
              }
            }
          }
        }
      }

      .data-bottom-box {
        height: 260px;
      }
    }
  }
</style>
